package net.sk.china.city.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import net.sk.china.city.domain.ArRegionRelation;
import net.sk.china.city.domain.ArRegionTreeSelect;
import net.sk.china.city.mapper.ArRegionRelationMapper;
import net.sk.china.common.exception.ServiceException;
import net.sk.china.city.utils.StringUtils;
import net.sk.china.city.service.IArRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.sk.china.city.mapper.ArRegionMapper;
import net.sk.china.city.domain.ArRegion;
import org.springframework.transaction.annotation.Transactional;

/**
 * 网格列表Service业务层处理
 *
 * @author yxf
 * @date 2024-05-28
 */
@Transactional
@Service
public class ArRegionServiceImpl implements IArRegionService {
    @Autowired
    private ArRegionMapper arRegionMapper;

    @Autowired
    private ArRegionRelationMapper arRegionRelationMapper;

    /**
     * 查询网格列表
     *
     * @param pkId 网格列表主键
     * @return 网格列表
     */
    @Override
    public ArRegion selectArRegionByPkId(Long pkId) {
        return arRegionMapper.selectArRegionByPkId(pkId);
    }

    /**
     * 查询网格列表列表
     *
     * @param arRegion 网格列表
     * @return 网格列表
     */
    @Override
    public List<ArRegion> selectArRegionList(ArRegion arRegion) {
        return arRegionMapper.selectArRegionList(arRegion);
    }

    /**
     * 查询网格树结构信息
     *
     * @param arRegion 网格信息
     * @return 部门树信息集合
     */
    @Override
    public List<ArRegionTreeSelect> selectArRegionTreeList(ArRegion arRegion) {
        List<ArRegion> arRegions = arRegionMapper.selectArRegionList(arRegion);
        return buildArRegionTreeSelect(arRegions);
    }

    /**
     * 新增网格列表
     *
     * @param arRegion 网格列表
     * @return 结果
     */
    @Override
    public int insertArRegion(ArRegion arRegion) {
        if (arRegion.getIsCell().equals(1) && (arRegion.getRegionCode() == null || arRegion.getRegionCode().isEmpty()))
            throw new ServiceException("网格编号不能为空", 400);
        else if (arRegion.getIsCell().equals(1) && arRegionMapper.getRegionCodeCount(arRegion.getRegionCode()) > 0)
            throw new ServiceException("网格编号重复", 400);
        if (!arRegion.getParentId().equals(0L)) {
            ArRegion parent = arRegionMapper.selectArRegionByPkId(arRegion.getParentId());
            arRegion.setAncestors(parent.getAncestors() + "," + parent.getPkId());
            arRegionMapper.insertArRegion(arRegion);

            boolean isCell = arRegion.getIsCell().equals(1);

            String[] split = arRegion.getAncestors().split(",");
            int i = split.length;
            for (String s : split) {
                if (!s.equals("0")) {
                    //关系表
                    ArRegionRelation arRegionRelation = new ArRegionRelation();
                    arRegionRelation.setAncestorId(Long.valueOf(s));
                    arRegionRelation.setDescendant(arRegion.getPkId());
                    arRegionRelation.setDistance((long) i);
                    arRegionRelationMapper.insertArRegionRelation(arRegionRelation);

                    //如果是网格则增加父节点网格数量
                    if (isCell) {
                        arRegionMapper.insertUpdateArRegionCellCount(Long.valueOf(s));
                    }
                }
                i--;
            }
            ArRegionRelation arRegionRelation = new ArRegionRelation();
            arRegionRelation.setAncestorId(arRegion.getPkId());
            arRegionRelation.setDescendant(arRegion.getPkId());
            arRegionRelation.setDistance((long) i);
            arRegionRelationMapper.insertArRegionRelation(arRegionRelation);
        } else {
            arRegion.setAncestors("0");
            arRegionMapper.insertArRegion(arRegion);
            ArRegionRelation arRegionRelation = new ArRegionRelation();
            arRegionRelation.setAncestorId(arRegion.getPkId());
            arRegionRelation.setDescendant(arRegion.getPkId());
            arRegionRelation.setDistance(0L);
            arRegionRelationMapper.insertArRegionRelation(arRegionRelation);
        }
        return 1;
    }

    /**
     * 修改网格列表
     *
     * @param arRegion 网格列表
     * @return 结果
     */
    @Override
    public int updateArRegion(ArRegion arRegion) {
        ArRegion arRegion1 = arRegionMapper.selectArRegionByPkId(arRegion.getPkId());
        if (arRegion.getIsCell().equals(1) && (arRegion.getRegionCode() == null || arRegion.getRegionCode().isEmpty()) && arRegion1.getRegionCode() == null)
            throw new ServiceException("网格编号不能为空", 400);
        else if (arRegion.getIsCell().equals(1) && (arRegion.getRegionCode() != null && !arRegion.getRegionCode().isEmpty()) && Objects.equals(arRegion1.getRegionCode(), arRegion.getRegionCode())) {
            //增加网格
            if (arRegion.getIsCell().equals(1) && arRegion1.getIsCell().equals(0)) {
                String[] split = arRegion1.getAncestors().split(",");
                for (String s : split) {
                    arRegionMapper.insertUpdateArRegionCellCount(Long.valueOf(s));
                }
            }
            return arRegionMapper.updateArRegion(arRegion);
        }
        else if (arRegion.getIsCell().equals(1) && arRegionMapper.getRegionCodeCount(arRegion.getRegionCode()) > 0)
            throw new ServiceException("网格编号重复", 400);

        //减少网格
        if (arRegion.getIsCell().equals(0) && arRegion1.getIsCell().equals(1)){
            String[] split = arRegion1.getAncestors().split(",");
            for (String s : split) {
                arRegionMapper.deleteUpdateArRegionCellCount(Long.valueOf(s));
            }
        }
        return arRegionMapper.updateArRegion(arRegion);
    }

    /**
     * 批量删除网格列表
     *
     * @param pkIds 需要删除的网格列表主键
     * @return 结果
     */
    @Override
    public int deleteArRegionByPkIds(Long[] pkIds) {
        return arRegionMapper.deleteArRegionByPkIds(pkIds);
    }

    /**
     * 删除网格列表信息
     *
     * @param pkId 网格列表主键
     * @return 结果
     */
    @Override
    public int deleteArRegionByPkId(Long pkId) {
        ArRegion arRegion = arRegionMapper.selectArRegionByPkId(pkId);
        if (arRegionMapper.getParentIdCount(pkId) > 0L)
            return 0;
        if (arRegionRelationMapper.deleteArRegionRelationByDescendant(pkId) == 0)
            return 0;
        if (arRegion.getIsCell().equals(1)) {
            String[] split = arRegion.getAncestors().split(",");
            for (String s : split) {
                if (!s.equals("0")) {
                    arRegionMapper.deleteUpdateArRegionCellCount(Long.valueOf(s));
                }
            }
        }
        return arRegionMapper.deleteArRegionByPkId(pkId);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param arRegions 网格列表
     * @return 下拉树结构列表
     */
    public List<ArRegionTreeSelect> buildArRegionTreeSelect(List<ArRegion> arRegions) {
        List<ArRegion> arRegionTrees = buildArRegionTree(arRegions);
        return arRegionTrees.stream().map(ArRegionTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param arRegions 网格列表
     * @return 树结构列表
     */
    public List<ArRegion> buildArRegionTree(List<ArRegion> arRegions) {
        List<ArRegion> returnList = new ArrayList<ArRegion>();
        List<Long> tempList = arRegions.stream().map(ArRegion::getPkId).collect(Collectors.toList());
        for (ArRegion arRegion : arRegions) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(arRegion.getParentId())) {
                recursionFn(arRegions, arRegion);
                returnList.add(arRegion);
            }
        }
        if (returnList.isEmpty()) {
            returnList = arRegions;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ArRegion> list, ArRegion t) {
        // 得到子节点列表
        List<ArRegion> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ArRegion tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ArRegion> getChildList(List<ArRegion> list, ArRegion t) {
        List<ArRegion> tlist = new ArrayList<ArRegion>();
        Iterator<ArRegion> it = list.iterator();
        while (it.hasNext()) {
            ArRegion n = (ArRegion) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getPkId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ArRegion> list, ArRegion t) {
        return getChildList(list, t).size() > 0;
    }
}
